package com.heima.ai.controller;

import com.heima.ai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RequiredArgsConstructor
@RestController
@RequestMapping("ai")
public class ChatController {

    private final ChatClient chatClient;
    private final ChatHistoryRepository chatHistoryRepository;

    @RequestMapping("/chat2")
    public String chat(String prompt){

        return chatClient.prompt().user(prompt).call().content();
    }


    @RequestMapping(value = "/chat3",produces = "text/html;charset=utf-8")
    public Flux<String> cha2(String prompt){

        return chatClient.prompt().user(prompt).stream().content();
    }

    @RequestMapping(value = "/chat4",produces = "text/html;charset=utf-8")
    public Flux<ChatResponse> cha3(String prompt){

        return chatClient.prompt().user(prompt).advisors(new SimpleLoggerAdvisor()).stream().chatResponse();
    }

    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> cha5(String prompt,String chatId){
        // 1. 保存会话id
        chatHistoryRepository.save("chat",chatId);
        // 2. 请求模型
        return chatClient.prompt()
                .user(prompt)
                // 增加记忆
                .advisors(a-> a.param(ChatMemory.CONVERSATION_ID,chatId))
                .stream()
                .content();
    }

}
